package com.wangdao.mall.dao;

import com.alibaba.druid.util.StringUtils;
import com.wangdao.mall.model.Admin;
import com.wangdao.mall.model.Password;
import com.wangdao.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:HaiyangTian
 * @Description:
 * @Date: Created in 17:37 2020/4/29
 * @Modified By:
 */
public class AdminDaoImp implements AdminDao {
    /**
     * 返回管理员登陆信息的查询结果（是否有相应匹配的管理员）
     * @param admin
     * @return
     */
    @Override
    public int login(Admin admin) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        try {
            Admin query = runner.query("select * from admin where email = ? and pwd = ?",
                    new BeanHandler<>(Admin.class),
                    admin.getEmail(), admin.getPwd());
            //用户名，密码正确
            if (query != null){
                return  200;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //用户名，密码错误
        return 500;
    }

    /**
     * 返回所有管理员用户的查询信息
     * @return
     */
    @Override
    public List<Admin> allAdmins() {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<Admin> admins = null;
        try {
            admins = runner.query("select * from admin",
                    new BeanListHandler<Admin>(Admin.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admins;
    }

    /**
     * 查询对应的管理员用户
     * @param params
     * @return
     */
    @Override
    public List<Admin> getSearchAdmins(Admin params) {
        Map<String,Object> dynamicSql = getDynamicSql(params);
        String sql = (String) dynamicSql.get("sql");
        List<String> paramList = (List<String>) dynamicSql.get("params");
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<Admin> admins = null;
        try {
            //最后参数位置可以是一个不定长的参数，所以把list转为数组
            admins = runner.query(sql, new BeanListHandler<Admin>(Admin.class),
                    paramList.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admins;
    }

    /**
     * 动态sql语句
     * 用来解决参数过多sql语句过于复杂的问题
     * @param params
     * @return
     */
    private Map<String, Object> getDynamicSql(Admin params) {
        //list用来存储sql语句占位符需要匹配的参数
        List<String> list = new ArrayList<>();
        String baseSql = "select * from admin where 1 = 1";
        if (!StringUtils.isEmpty(params.getEmail())){
            baseSql = baseSql + " and email like ?";
            list.add("%" + params.getEmail() + "%");
        }
        if (!StringUtils.isEmpty(params.getNickname())){
            baseSql = baseSql + " and nickname like ?";
            list.add("%" + params.getNickname() + "%");
        }
        //用map的方式来存储动态sql语句和他的参数
        Map<String, Object> map = new HashMap<>();
        map.put("sql",baseSql);
        map.put("params",list);
        return map;
    }

    /**
     * 删除管理员用户信息
     * @param id
     */
    @Override
    public int deleteAdmins(String id) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        int row = 0;
        try {
            row = runner.update("delete from admin where id = ?", id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    /**
     * 向数据库中添加数据
     * @param admin
     * @return
     */
    @Override
    public int addAdmins(Admin admin) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        //sql语句影响的行数，正常执行就是1行
        //因为nickname和email都是唯一键，所以重复会添加失败
        int row = 0;
        try {
            row = runner.update("insert into admin(nickname,email,pwd) values (?,?,?)",
                    admin.getNickname(), admin.getEmail(), admin.getPwd());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    /**
     * 更改数据库中的密码
     * @param pwds
     * @return
     */
    @Override
    public int changePwd(Password pwds,String admin) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        int row = 0;
        try {
            Admin query = runner.query("select pwd from admin where email = ?",
                    new BeanHandler<>(Admin.class), admin);
            if (!query.getPwd().equals(pwds.getOldPwd())) {
                return row;
            }
            row = runner.update("update admin set pwd = ? where email = ?", pwds.getNewPwd(),admin);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    /**
     * 获取这个管理员的用户信息
     * @param id
     * @return
     */
    @Override
    public Admin getAdminsInfo(String id) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        Admin admin = null;
        try {
            admin = runner.query("select * from admin where id = ?",
                    new BeanHandler<>(Admin.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admin;
    }

    /**
     * 更新对应管理员信息
     * @param admin
     */
    @Override
    public void updateAdmins(Admin admin) {
        Map<String,Object> update = getUpdateSql(admin);
        String sql = (String) update.get("sql");
        List<String> params = (List<String>) update.get("params");
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        try {
            runner.update(sql,params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 动态获取更新数据的sql
     * @param admin
     * @return
     */
    private Map<String, Object> getUpdateSql(Admin admin) {
        Map<String, Object> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        StringBuffer buffer = new StringBuffer();
        buffer.append("update admin set");
        buffer.append(" email = ? ,");
        list.add(admin.getEmail());
        buffer.append(" nickname = ? ,");
        list.add(admin.getNickname());
        buffer.append(" pwd = ? ,");
        list.add(admin.getPwd());
        buffer.deleteCharAt(buffer.length() - 1);
        buffer.append("where id = ?");
        list.add(admin.getId().toString());
        map.put("sql",buffer.toString());
        map.put("params",list);
        return map;
    }
}
